package com.futvan.z.framework.core;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.util.StringUtil;
/**
 * 统一异常处理类
 * @author zz
 * @CreateDate 2018-07-16
 */
public class AllExceptionHandler extends SuperZ implements HandlerExceptionResolver {

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {
		
		
		if(handler instanceof HandlerMethod) {
			//获取请求方面对象,判读是页面跳转请求，或是json接口请求
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method, ResponseBody.class);
			if(responseBodyAnn!=null) {
				//JSON接口异常
				ModelAndView mv = new ModelAndView();
				FastJsonJsonView view = new FastJsonJsonView();
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("code", Code.ERROR); 
				attributes.put("msg", StringUtil.ExceptionToString(ex)); 
				view.setAttributesMap(attributes);
				mv.setView(view); 
				return mv;
			}else {
				//页面跳转请求异常
				Map<String, Object> model = new HashMap<String, Object>(); 
				model.put("ex", StringUtil.ExceptionToString(ex)); 
				return new ModelAndView("common/error/500", model);
			}
		}else {
			//输出异常到日志文件
			z.Error(ex.getMessage(),ex);
			 return null;
		}

	}

}
